package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.exceptions.bank.ClientsExistsException;

import java.io.*;

public class BankService {
    File serializationFile;

    public BankService(File serializationFile) {
        this.serializationFile = serializationFile;
    }

    public Bank createNewBank() {
        Bank result =  new Bank();
        saveBank(result);
        return result;
    }

    public Client addClient(Bank bank, Client client) throws ClientsExistsException {
        bank.addClient(client);
        saveBank(bank);
        return  client;
    }

    public void printBalance(Bank bank) {
        StringBuffer buffer = new StringBuffer();
        for (Client c : bank.getClients()) {
            for (Account acc : c.getAccounts()) {
                buffer.append(acc).append("\n");
            }
        }
        System.out.println(buffer);
    }

    public void printMaximumAmountToWithdraw(Bank bank) {
        for (Client c : bank.getClients()) {
            for (Account acc : c.getAccounts()) {

                System.out.println(acc);
            }
        }
    }

    public Bank readBank() throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(this.serializationFile));
        Bank result =  (Bank) in.readObject();
        in.close();
        return result;
    }

    public void saveBank(Bank bank) {
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(this.serializationFile));
            out.writeObject(bank);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
